import base64
import json
from json import JSONDecodeError
import os


from locust import task,FastHttpUser,wait_time,constant,tag,between,run_single_user, constant_pacing,constant_throughput

index_cookie = 2000
def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('../cookie.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])

def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')

class MyTask(FastHttpUser):
    # wait_time = constant_throughput(2000)
    # wait_time = between(1, 2)
    wait_time = constant(1)
    host = "https://www.retone-hearing.fit"
    # host = "https://192.168.10.233:8081"
    header =  {"Cookie": "hearingaid_user=NmE1YWQyZmMtZGMzZC00OGU2LWI5NTgtN2IxMzNjZjRjMDQw",
                           "Content-Type": "application/json"}

    @task
    @tag('getLoginState')
    def getLoginState(self):
        url = '/microServiceUser/responseEncode/requestDecode/getLoginState'
        with self.client.post(url, headers = self.header,catch_response=True) as resp:
            try:
                if resp.status_code != 200 or resp.json()['data'] == None:
                    resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                else:
                    # print(resp.json())
                    resp.success()
            except JSONDecodeError:
                resp.failure("Response could not be decoded as JSON")
            except KeyError:
                resp.failure("Response did not contain expected key 'greeting'")


if __name__ == '__main__':
    os.system('locust -f locust_loginstatus.py --web-host="127.0.0.1"')
    # run_single_user(MyTask)